﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.COM;
using MINERP.MODEL.OverOrder;

using MINERP.DAL.OverOrder;
using MINERP.MODEL.FoundationModel;
using System.Transactions;
using MINERP.DAL.CommonDAL;
using MINERP.DAL;
using MINERP.MODEL.DisjoinProForOutShop;
using System.Data;
namespace MINERP.BLL.OverOrderBLL
{
    /// <summary>
    /// 结点操作BLL
    /// </summary>
    public class OverOrderBLL
    {
        OrverOrderDAL _dal;
        WorkFlowListDAL _workDAL;
        OutProcessRecordDAL _outRecordDAL;
        OrderInfoDAL _orderinfoDAL;
        UsersDAL _userDAL;
        OutShopDAL _outShopDal;

        //private List<OutProcessShop> _outShopList;
        private List<int> _PreSelectedOrderProductIdList;//上面数据（_outShop）对应的产品ID

        public OverOrderBLL()
        {
            if (_dal == null)
            {
                _dal = new OrverOrderDAL();
            }
            if (_workDAL == null)
            {
                _workDAL = new WorkFlowListDAL();
            }
            if (_outRecordDAL == null)
            {
                _outRecordDAL = new OutProcessRecordDAL();
            }
            if (_orderinfoDAL == null)
            {
                _orderinfoDAL = new OrderInfoDAL();
            }
            if (_userDAL == null)
            {
                _userDAL = new UsersDAL();
            }
            if (_outShopDal == null)
            {
                _outShopDal = new OutShopDAL();
            }
        }

        /// <summary>
        /// 根据状态获得主任务列表(deleted)
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public List<OverOrderView> GetMainTaskByStatus(OrderInfoStatus status)
        {
            List<orderInfo> OrderList = _dal.GetOrdersByStatus(status);
            if (OrderList.Count < 1)
            {
                return null;
            }
            else
            {
                return GetOverViewFromModel(OrderList);
            }
        }

        public List<OverOrderView> GetMainTasks(int techId, OrderInfoStatus status)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<orderInfo> OrderList = new List<orderInfo>();

                // List<orderInfo> OrderList = _dal.GetOrdersByCurrTechId(techId, status, db);
                List<WorkOrderFlowList> listWFL = db.WorkOrderFlowList.Where(wfl => wfl.tb_Tech.TechId == techId && wfl.Status == (int)OrderFlowListStatus.Useable && wfl.orderInfo.OutProcessRecord.Count < 1).ToList();


                foreach (var item in listWFL)
                {
                    if (!item.orderInfoReference.IsLoaded)
                    {
                        item.orderInfoReference.Load();
                    }
                    if (!item.orderInfo.OutProcessRecord.IsLoaded)
                    {
                        item.orderInfo.OutProcessRecord.Load();
                    }
                    OrderList.Add(item.orderInfo);
                }
                if (OrderList.Count < 1)
                {
                    return null;
                }
                else
                {
                    return GetOverViewFromModel(OrderList);
                }
            }
        }
        public DataTable GetOuttingTask()
        {
            return _dal.GetOuttingTask();
        }
        public DataTable GetOrderProductCode()
        {
            return _dal.GetOrderProductCode();
        }
        public DataTable GetProductName()
        {
            return _dal.GetProductName();
        }
        public DataTable GetShop()
        {
            return _dal.GetShop();
        }
        public DataTable GetCtmName(int inShopId)
        {
            return _dal.GetCtmName(inShopId);
        }
        public DataTable GetOutShop()
        {
            return _dal.GetOutShop();
        }
        public DataTable GetPriority()
        {
            return _dal.GetPriority();
        }
        public DataTable GetCreateUser()
        {
            return _dal.GetCreateUser();
        }

        public DataTable GetOuttingTaskByBarCode(string inBarCode)
        {
            return _dal.GetOuttingTaskByBarCode(inBarCode);
        }
        #region helper methods

        private List<OutProcessShop_Info> ConvertOutProcessShop_InfoFromOutProcessShop(IEnumerable<OutProcessShop> OriginalList)
        {
            List<OutProcessShop_Info> result = new List<OutProcessShop_Info>();
            if (OriginalList == null)
            {
                return new List<OutProcessShop_Info>();
            }
            foreach (var item in OriginalList)
            {
                OutProcessShop_Info info = new OutProcessShop_Info() { Addr = item.Addr, City = item.City, Code = item.Code, IsUse = item.IsUse, Keeper = item.Keeper, OutShopId = item.OutShopId, OutShopName = item.OutShopName, Remark = item.Remark, Tel1 = item.Tel1, Tel2 = item.Tel2, Type = item.Type };
                if (!item.Tb_OutShop_ProductCategory.IsLoaded)
                {
                    item.Tb_OutShop_ProductCategory.Load();
                }
                foreach (var tbtemp in item.Tb_OutShop_ProductCategory)
                {
                    if (!tbtemp.Tb_ProductReference.IsLoaded)
                    {
                        tbtemp.Tb_ProductReference.Load();
                    }
                    if (info.ProductsList == null)
                    {
                        info.ProductsList = new List<Tb_Product_Info>();
                    }

                    info.ProductsList.Add(new Tb_Product_Info() { Height = tbtemp.Tb_Product.Height, PageNum = tbtemp.Tb_Product.PageNum, ProductCode = tbtemp.Tb_Product.ProductCode, ProductDes = tbtemp.Tb_Product.ProductDes, ProductName = tbtemp.Tb_Product.ProductName, ProuctId = tbtemp.Tb_Product.ProuctId, Width = tbtemp.Tb_Product.Width });
                }
                result.Add(info);
            }

            return result;
        }

        /// <summary>
        /// 得到委外加工商加工某一产品所需要的时间
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <param name="outShopId"></param>
        /// <returns></returns>
        /// 
        private double GetHours(int orderProductId, int outShopId)
        {
            orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);
            return GetHours(oi, outShopId);
        }

        private double GetHours(orderInfo oi, OutProcessShop outShop)
        {
            int productId;
            if (!oi.Tb_ProductReference.IsLoaded)
            {
                oi.Tb_ProductReference.Load();
            }
            productId = oi.Tb_Product.ProuctId;

            if (!outShop.Tb_OutShop_ProductCategory.IsLoaded)
            {
                outShop.Tb_OutShop_ProductCategory.Load();
            }
            Tb_OutShop_ProductCategory temp = outShop.Tb_OutShop_ProductCategory.First(p => p.ProductId == productId);

            return Convert.ToDouble(temp.NeedTime);
        }

        private double GetHours(orderInfo oi, int outShopId)
        {
            OutProcessShop outShop = _outShopDal.GetOneById(outShopId);
            return GetHours(oi, outShop);
        }

        internal GridDetailBase GetGridDetailBaseFromOrderinfo(orderInfo orderinfo)
        {
            //List<GridDetailBase> listView = new List<GridDetailBase>();
            GridDetailBase orderView;
            //foreach (var orderinfo in orderList)
            //{
            if (!orderinfo.Tb_OrderBagReference.IsLoaded)//定单包
            {
                orderinfo.Tb_OrderBagReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.usersReference.IsLoaded)//开单人
            {
                orderinfo.Tb_OrderBag.usersReference.Load();
            }
            if (!orderinfo.Tb_ProductReference.IsLoaded)//产品
            {
                orderinfo.Tb_ProductReference.Load();
            }
            if (!orderinfo.Tb_OrderBag.ShopReference.IsLoaded)//商户
            {
                orderinfo.Tb_OrderBag.ShopReference.Load();
            }

            if (!orderinfo.OutProcessRecord.IsLoaded)
            {
                orderinfo.OutProcessRecord.Load();
            }
            if (!orderinfo.photoInfo.IsLoaded)
            {
                orderinfo.photoInfo.Load();
            }


            orderView = new OverOrderView();
            orderView.IsPrint = true;
            orderView.photoNum = orderinfo.photoInfo.Count;
            orderView.OrderProductInfo = new OrderInfo_Info() { ShopName = orderinfo.Tb_OrderBag.Shop.shopName, CompleteTime = orderinfo.CompleteTime, CtmName = orderinfo.CtmName, Height = orderinfo.Height, IsEdit = orderinfo.IsEdit, OrderPath = orderinfo.OrderPath, OrderProductCode = orderinfo.OrderProductCode, OrderProductId = orderinfo.OrderProductId, OrderProductName = orderinfo.OrderProductName, OrilOrderPath = orderinfo.OrilOrderPath, PageNum = orderinfo.PageNum, ProductNum = orderinfo.productNum, Remark = orderinfo.Remark, Status = orderinfo.status, Width = orderinfo.Width };
            orderView.OrderBagInfo = new Tb_OrderBag_Info() { BagCode = orderinfo.Tb_OrderBag.BagCode, ShopID = orderinfo.Tb_OrderBag.Shop.ShopId, BagName = orderinfo.Tb_OrderBag.BagName, CompleteTime = orderinfo.Tb_OrderBag.CompleteTime, FetchTime = orderinfo.Tb_OrderBag.FetchTime, OrderBagId = orderinfo.Tb_OrderBag.OrderBagId, OrderTime = orderinfo.Tb_OrderBag.OrderTime, Priority = orderinfo.Tb_OrderBag.Priority, Remark = orderinfo.Tb_OrderBag.Remark, ShopName = orderinfo.Tb_OrderBag.Shop.shopName, Status = orderinfo.Tb_OrderBag.Status, Type = orderinfo.Tb_OrderBag.Type, UserID = orderinfo.Tb_OrderBag.users.userID };
            orderView.ProductInfo = new Tb_Product_Info() { Height = orderinfo.Tb_Product.Height, PageNum = orderinfo.Tb_Product.PageNum, ProductName = orderinfo.Tb_Product.ProductName, ProductCode = orderinfo.Tb_Product.ProductCode, ProductDes = orderinfo.Tb_Product.ProductDes, Width = orderinfo.Tb_Product.Width };
            //}

            return orderView;
        }

        /// <summary>
        /// 将OrderInfo实体列表封装成OverOrderView对象
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        private List<OverOrderView> GetOverViewFromModel(List<orderInfo> orderList)
        {
            List<OverOrderView> listView = new List<OverOrderView>();
            OverOrderView orderView;
            foreach (var orderinfo in orderList)
            {
                //if (!orderinfo.Tb_OrderBagReference.IsLoaded)//定单包
                //{
                //    orderinfo.Tb_OrderBagReference.Load();
                //}
                //if (!orderinfo.Tb_OrderBag.usersReference.IsLoaded)//开单人
                //{
                //    orderinfo.Tb_OrderBag.usersReference.Load();
                //}
                //if (!orderinfo.Tb_ProductReference.IsLoaded)//产品
                //{
                //    orderinfo.Tb_ProductReference.Load();
                //}
                //if (!orderinfo.Tb_OrderBag.ShopReference.IsLoaded)//商户
                //{
                //    orderinfo.Tb_OrderBag.ShopReference.Load();
                //}

                //if (!orderinfo.OutProcessRecord.IsLoaded)
                //{
                //    orderinfo.OutProcessRecord.Load();
                //}


                //orderView = new OverOrderView();
                //orderView.OrderProductInfo = new OrderInfo_Info() { CompleteTime = orderinfo.CompleteTime, CtmName = orderinfo.CtmName, Height = orderinfo.Height, IsEdit = orderinfo.IsEdit, OrderPath = orderinfo.OrderPath, OrderProductCode = orderinfo.OrderProductCode, OrderProductId = orderinfo.OrderProductId, OrderProductName = orderinfo.OrderProductName, OrilOrderPath = orderinfo.OrilOrderPath, PageNum = orderinfo.PageNum, ProductNum = orderinfo.productNum, Remark = orderinfo.Remark, Status = orderinfo.status, Width = orderinfo.Width };
                //orderView.OrderBagInfo = new Tb_OrderBag_Info() { BagCode = orderinfo.Tb_OrderBag.BagCode, ShopID = orderinfo.Tb_OrderBag.Shop.ShopId, BagName = orderinfo.Tb_OrderBag.BagName, CompleteTime = orderinfo.Tb_OrderBag.CompleteTime, FetchTime = orderinfo.Tb_OrderBag.FetchTime, OrderBagId = orderinfo.Tb_OrderBag.OrderBagId, OrderTime = orderinfo.Tb_OrderBag.OrderTime, Priority = orderinfo.Tb_OrderBag.Priority, Remark = orderinfo.Tb_OrderBag.Remark, ShopName = orderinfo.Tb_OrderBag.Shop.shopName, Status = orderinfo.Tb_OrderBag.Status, Type = orderinfo.Tb_OrderBag.Type, UserID = orderinfo.Tb_OrderBag.users.userID };
                //orderView.ProductInfo = new Tb_Product_Info() { Height = orderinfo.Tb_Product.Height, PageNum = orderinfo.Tb_Product.PageNum, ProductName = orderinfo.Tb_Product.ProductName, ProductCode = orderinfo.Tb_Product.ProductCode, ProductDes = orderinfo.Tb_Product.ProductDes, Width = orderinfo.Tb_Product.Width };

                orderView = (OverOrderView)GetGridDetailBaseFromOrderinfo(orderinfo);
                orderView.IsPrint = false;
                if (orderinfo.OutProcessRecord.Count > 0)
                {
                    OutProcessRecord opr = orderinfo.OutProcessRecord.First();
                    if (!opr.OutProcessShopReference.IsLoaded)
                    {
                        opr.OutProcessShopReference.Load();
                    }
                    if (!opr.usersReference.IsLoaded)//FetchUser
                    {
                        opr.usersReference.Load();
                    }
                    if (!opr.users1Reference.IsLoaded)//createUser
                    {
                        opr.users1Reference.Load();
                    }
                    if (opr.Status == (int)OutProcessRecordStatus.InGrid)
                    {
                        orderView.IsPrint = true;
                    }
                    orderView.OutRecordInfo = new OutProcessRecord_Info() { OutProcessRecordId = opr.OutProcessRecordId, CreateTime = opr.CreateTime, CreateUser = opr.users1.UserName, FetchUser = opr.users1.UserName, FetchRemark = opr.FetchRemark, FetchTime = (opr.FetchTime == null) ? DateTime.Now : (DateTime)opr.FetchTime, OutRemark = opr.OutRemark, PreFetchTime = opr.PreFetchTime, Status = opr.Status, OutShopInfo = new OutProcessShop_Info() { OutShopId = opr.OutProcessShop.OutShopId, OutShopName = opr.OutProcessShop.OutShopName } };
                }
                else
                {
                    //orderView.OutRecordInfo = new OutProcessRecord_Info() { CreateUser = orderinfo.OutProcessRecord.CreateUser.UserName, FetchUser = orderinfo.OutProcessRecord.CreateUser.UserName, FetchRemark = orderinfo.OutProcessRecord.FetchRemark, FetchTime = (DateTime)orderinfo.OutProcessRecord.FetchTime, OutRemark = orderinfo.OutProcessRecord.OutRemark, PreFetchTime = orderinfo.OutProcessRecord.PreFetchTime, Status = orderinfo.OutProcessRecord.Status };
                    orderView.OutRecordInfo = new OutProcessRecord_Info();
                    orderView.OutRecordInfo.OutShopInfo = new OutProcessShop_Info();
                }

                listView.Add(orderView);
            }

            return listView;
        }

        /// <summary>
        /// 直接结单
        /// </summary>
        /// <param name="orderProductId">orderinfo的ID</param>
        void DirectOverOrder(int orderProductId)
        {
            //标记状态为完成
            WorkOrderFlowList wfl = _workDAL.GetOneWorkFlowList(orderProductId, OrderFlowListStatus.Useable);
            wfl.Status = (int)OrderFlowListStatus.Complete;

            //OutProcessRecord outRecord = _outRecordDAL.GetOneByOrderProductId(orderProductId);
            //修改ORDERINFO的状态
            orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);
            oi.status = (int)OrderInfoStatus.OverOrder;

            bool isALLOver = true;//此单对应的定单包的包的定单是否都以完成
            if (!oi.Tb_OrderBagReference.IsLoaded)
            {
                oi.Tb_OrderBagReference.Load();
            }
            if (!oi.Tb_OrderBag.orderInfo.IsLoaded)
            {
                oi.Tb_OrderBag.orderInfo.Load();
            }
            foreach (var item in oi.Tb_OrderBag.orderInfo)
            {
                if (item.status != (int)OrderInfoStatus.OverOrder)
                {
                    isALLOver = false;//只要有一个不为OVER就退出结束
                    break;
                }
            }
            if (isALLOver)//修改tb_orderBag的状态
            {
                oi.Tb_OrderBag.Status = (int)OrderBagStatus.Completed;
            }
        }

        /// <summary>
        /// 收件和直接结单
        /// </summary>
        /// <param name="orderProductId"></param>
        void FetchAndOver(int orderProductId, string fetchRemark, int fetchUid)
        {
            OutProcessRecord outRecord = _outRecordDAL.GetOneByOrderProductId(orderProductId);
            outRecord.FetchRemark = fetchRemark;
            outRecord.users = UsersDAL.GetOneById(fetchUid);
            outRecord.Status = (int)OutProcessRecordStatus.Fetched;

            DirectOverOrder(orderProductId);
        }


        #endregion helper methods

        /// <summary>
        /// 结单列表中的orderInfo中的定单产品,直接结单
        /// </summary>
        /// <param name="OrderProductList">orderinfo表的id</param>
        public void OverOrder(List<int> OrderProductList)
        {
            foreach (var orderProductId in OrderProductList)
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        DirectOverOrder(orderProductId);

                        DALBase.Save();
                        ts.Complete();

                    }
                    catch (Exception ex)
                    {
                        //将ex写入相关日志
                        throw new Exception("结单出错，请信息相关人员");
                    }

                }
            }

        }

        /// <summary>
        /// 获得某个委外加工商的任务列表
        /// </summary>
        /// <param name="OutShopId">委外加工商ID</param>
        /// <returns></returns>
        public List<OverOrderView> GetShopTaskViewByOutShopId(int outShopId)
        {
            if (outShopId < 1)
            {
                return null;
            }
            else
            {
                // List<OutProcessRecord> recordList = _dal.GetAllOutRecordByOutShopId(outShopId);
                List<OutProcessRecord> recordList = _dal.GetAllOutRecordByOutShopIdInGrid(outShopId);
                if (recordList.Count < 1)
                {
                    return null;
                }
                else
                {
                    List<orderInfo> orderList = new List<orderInfo>();
                    foreach (var record in recordList)
                    {
                        if (!record.orderInfoReference.IsLoaded)
                        {
                            record.orderInfoReference.Load();
                        }
                        orderList.Add(record.orderInfo);
                    }

                    return GetOverViewFromModel(orderList);
                }
            }
        }

        /// <summary>
        /// 获得某个委外加工商的任务列表
        /// </summary>
        /// <param name="OutShopId">委外加工商ID</param>
        /// <returns></returns>
        public List<OverOrderView> GetShopTaskViewByOutShopIdForList(int outShopId)
        {
            if (outShopId < 1)
            {
                return null;
            }
            else
            {
                List<OutProcessRecord> recordList = _dal.GetAllOutRecordByOutShopId(outShopId);
                // List<OutProcessRecord> recordList = _dal.GetAllOutRecordByOutShopIdInGrid(outShopId);
                if (recordList.Count < 1)
                {
                    return null;
                }
                else
                {
                    List<orderInfo> orderList = new List<orderInfo>();
                    foreach (var record in recordList)
                    {
                        if (!record.orderInfoReference.IsLoaded)
                        {
                            record.orderInfoReference.Load();
                        }
                        orderList.Add(record.orderInfo);
                    }

                    return GetOverViewFromModel(orderList);
                }
            }
        }
        /// <summary>
        /// 将加工任务从某个加工商取消
        /// </summary>
        /// <param name="cancelList"></param>
        //public int CancelOutShopTask(List<int> cancelList)
        //{
        //    foreach (var orderProductId in cancelList)
        //    {
        //        using (TransactionScope ts = new TransactionScope())
        //        {
        //            try
        //            {
        //                //orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);

        //                OutProcessRecord outRecord = _outRecordDAL.GetOneByOrderProductId(orderProductId);
        //                if (outRecord.Status == (int)OutProcessRecordStatus.Fetched)
        //                {
        //                    return 0;//不能取消，因为该任务正在已经取件
        //                }
        //                else if (outRecord.Status == (int)OutProcessRecordStatus.Outing)
        //                {
        //                    OutShopBillDetail billDetail = _outRecordDAL.GetDetail(orderProductId);

        //                    billDetail.OutShop_BillReference.Load();
        //                    OutShop_Bill bill = billDetail.OutShop_Bill;
        //                    if (billDetail.PayStatus == (int)OutProcessProductStatus.Outting)
        //                    {
        //                        bill.Summed = bill.Summed - billDetail.Num * billDetail.UnitPrice;
        //                    }
        //                    else if (billDetail.PayStatus == (int)OutProcessProductStatus.Received)
        //                    {
        //                        bill.Summed = bill.Summed - billDetail.Num * billDetail.UnitPrice;
        //                        bill.SummedRecive = bill.SummedRecive - billDetail.Num * billDetail.UnitPrice;
        //                    }
        //                    _outRecordDAL.DelOutShopBillDetail(billDetail);
        //                }
        //                _outRecordDAL.Delete(outRecord);


        //                //oi.status = (int)OrderInfoStatus.FenPianCompleted;

        //                DALBase.Save();
        //                ts.Complete();
        //            }
        //            catch
        //            {
        //                return -1;
        //                //throw new Exception("取消失败，请与相关人员联系！");
        //            }
        //        }
        //    }
        //    return 1;
        //}
        public int CancelOutShopTask(List<int> cancelList)
        {
            using(newSampleYPDBEntities db =new newSampleYPDBEntities())
            foreach (var orderProductId in cancelList)
            {
                //using (TransactionScope ts = new TransactionScope())
                //{
                    try
                    {
                        //orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);

                       // OutProcessRecord outRecord = _outRecordDAL.GetOneByOrderProductId(orderProductId);
                        OutProcessRecord outRecord = db.OutProcessRecord.First(p => p.orderInfo.OrderProductId == orderProductId); ;
                        if (outRecord.Status == (int)OutProcessRecordStatus.Fetched)
                        {
                            return 0;//不能取消，因为该任务正在已经取件
                        }
                        else if (outRecord.Status == (int)OutProcessRecordStatus.Outing)
                        {
                            //OutShopBillDetail billDetail = _outRecordDAL.GetDetail(orderProductId);
                            string barcode = "2" + string.Format("{0:D9}", orderProductId);
                            //return DataEntites.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == barcode);
                            OutShopBillDetail billDetail = db.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == barcode);
                            billDetail.OutShop_BillReference.Load();
                            OutShop_Bill bill = billDetail.OutShop_Bill;
                            if (billDetail.PayStatus == (int)OutProcessProductStatus.Outting)
                            {
                                bill.Summed = bill.Summed - billDetail.Num * billDetail.UnitPrice;
                            }
                            else if (billDetail.PayStatus == (int)OutProcessProductStatus.Received)
                            {
                                bill.Summed = bill.Summed - billDetail.Num * billDetail.UnitPrice;
                                bill.SummedRecive = bill.SummedRecive - billDetail.Num * billDetail.UnitPrice;
                            }
                            //_outRecordDAL.DelOutShopBillDetail(billDetail);
                            db.DeleteObject(billDetail);
                        }
                        else if (outRecord.Status == (int)OutProcessRecordStatus.InGrid)
                        {

                        }
                        else
                        {
 
                        }
                        //_outRecordDAL.Delete(outRecord);
                        db.DeleteObject(outRecord);

                        //oi.status = (int)OrderInfoStatus.FenPianCompleted;

                       
                    }
                    catch
                    {
                        return -1;
                        //throw new Exception("取消失败，请与相关人员联系！");
                    }
                    db.SaveChanges();
                //}
            }
            return 1;
        }
        /// <summary>
        /// 分配委外任务
        /// </summary>
        /// <param name="AssignOutlList">要委外的产品列表,OrderProductId</param>
        /// <param name="outShopId">委外的加工商</param>
        public void AssignOutTask(List<int> AssignOutlList, int outShopId, int userID, string outRemark)
        {
            foreach (var orderProductId in AssignOutlList)
            {
                //using (TransactionScope ts = new TransactionScope())
                //{
                //    try
                //    {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    OutProcessRecord hr = db.OutProcessRecord.FirstOrDefault(p => p.orderInfo.OrderProductId == orderProductId);
                    if (hr == null)
                    {
                        orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);
                        //oi.status = (int)OrderInfoStatus.OutProcess;

                        users operateUser = UsersDAL.GetOneById(userID);
                        OutProcessRecord outReocrd = new OutProcessRecord();
                        outReocrd.CreateTime = DateTime.Now;
                        outReocrd.users1 = operateUser;
                        outReocrd.FetchRemark = " ";
                        OutProcessShop outShop = _outShopDal.GetOneById(outShopId);
                        outReocrd.OutProcessShop = outShop;

                        DateTime fetchTime = DateTime.Now.AddHours(GetHours(oi, outShop));
                        outReocrd.FetchTime = fetchTime;
                        outReocrd.PreFetchTime = fetchTime;
                        outReocrd.users = operateUser;//默认为操作员
                        outReocrd.orderInfo = oi;


                        outReocrd.OutRemark = outRemark;
                        outReocrd.Status = (int)OutProcessRecordStatus.OutWaitFenDui;
                        _userDAL.AddNew(outReocrd);
                        DALBase.Save();
                    }
                }



                //        ts.Complete();

                //    }
                //    catch (Exception)
                //    {
                //        //记录日志
                //        throw new Exception("委外错误!");
                //    }
                //}

                //    using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                //{
                //    foreach (var orderProductId in AssignOutlList)
                //    {
                //        //using (TransactionScope ts = new TransactionScope())
                //        //{
                //        //    try
                //        //    {

                //        //orderInfo oi = _orderinfoDAL.GetOneById(orderProductId);
                //        //oi.status = (int)OrderInfoStatus.OutProcess;

                //        orderInfo oi = db.orderInfo.Where(p => p.OrderProductId == orderProductId).FirstOrDefault();

                //        users operateUser = db.users.Where(p => p.userID == userID).FirstOrDefault();
                //        OutProcessRecord outReocrd = new OutProcessRecord();
                //        outReocrd.CreateTime = DateTime.Now;
                //        outReocrd.users1 = operateUser;
                //        outReocrd.FetchRemark = " ";
                //        //OutProcessShop outShop = _outShopDal.GetOneById(outShopId);
                //        OutProcessShop outShop = db.OutProcessShop.Where(p => p.OutShopId == outShopId).FirstOrDefault() ;
                //        outReocrd.OutProcessShop = outShop;

                //        if (!oi.Tb_ProductReference.IsLoaded)
                //        {
                //            oi.Tb_ProductReference.Load();
                //        }
                //        int productId = oi.Tb_Product.ProuctId;

                //        if (!outShop.Tb_OutShop_ProductCategory.IsLoaded)
                //        {
                //            outShop.Tb_OutShop_ProductCategory.Load();
                //        }
                //        Tb_OutShop_ProductCategory temp = outShop.Tb_OutShop_ProductCategory.First(p => p.ProductId == productId);


                //       // DateTime fetchTime = DateTime.Now.AddHours(GetHours(oi, outShop));
                //         DateTime fetchTime = DateTime.Now.AddHours(temp.NeedTime);
                //        outReocrd.FetchTime = fetchTime;
                //        outReocrd.PreFetchTime = fetchTime;
                //        outReocrd.users = operateUser;//默认为操作员
                //        outReocrd.orderInfo = oi;

                //        outReocrd.OutRemark = outRemark;
                //        outReocrd.Status = (int)OutProcessRecordStatus.OutWaitFenDui;
                //        //_userDAL.AddNew(outReocrd);
                //        db.AddToOutProcessRecord(outReocrd);
                //        db.SaveChanges() ;
                //        //        ts.Complete();

                //        //    }
                //        //    catch (Exception)
                //        //    {
                //        //        //记录日志
                //        //        throw new Exception("委外错误!");
                //        //    }
                //        //}
                //  }
            }
        }

        /// <summary>
        /// 收件并结单--间接结单
        /// </summary>
        /// <param name="list"></param>
        public void FetchAndOrderOrder(List<int> OrderProductList, string fetchRemak, int userId)
        {
            foreach (var orderProductId in OrderProductList)
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        FetchAndOver(orderProductId, fetchRemak, userId);

                        DALBase.Save();
                        ts.Complete();

                    }
                    catch (Exception ex)
                    {
                        //将ex写入相关日志
                        throw new Exception("收件出错，请信息相关人员");
                    }

                }
            }
        }


        List<OutProcessShop_Info> list = new List<OutProcessShop_Info>();
        /// <summary>
        /// 根据orderinfo表的ID得到这些对应的产品对应的加工商有哪些
        /// </summary>
        /// <param name="productOrderIdList"></param>
        /// <returns></returns>
        public List<OutProcessShop_Info> GetOutShops(List<int> productOrderIdList)
        {
            List<OutProcessShop> currentList = null;

            //if (_outShopList == null)//新的
            //{
            _PreSelectedOrderProductIdList = productOrderIdList;
            foreach (var orderProductId in _PreSelectedOrderProductIdList)
            {
                List<OutProcessShop> listTemp = _outShopDal.getShopByOrderProductId(orderProductId);
                if (currentList == null)
                {
                    currentList = listTemp;
                }
                else//求交集
                {
                    currentList = (currentList.Intersect<OutProcessShop>(listTemp)).ToList<OutProcessShop>();
                    if (currentList == null)
                    {
                        break;
                    }
                }
            }

            //}
            //else//已有数据
            //{
            //    List<int> newPorductId = new List<int>();
            //    List<int> InertResult = (_PreSelectedOrderProductIdList.Intersect<int>(productOrderIdList)).ToList<int>();                
            //    if (InertResult.SequenceEqual<int>(productOrderIdList))//如果新的是旧的子集
            //    {
            //        foreach (var orderproductid in productOrderIdList)
            //        {
            //            newPorductId.Add(_orderinfoDAL.GetProductIdById(orderproductid));
            //        }



            //    }
            //}


            return ConvertOutProcessShop_InfoFromOutProcessShop(currentList);
        }
        public List<OutProcessShop_Info> GetOutShopList()
        {
            List<OutProcessShop_Info> rtnList = new List<OutProcessShop_Info>();
            OutProcessShop_Info shop = new OutProcessShop_Info() { OutShopId = 0, OutShopName = "全部" };
            rtnList.Add(shop);
            List<OutProcessShop> outShopList = _outShopDal.GetAllOutShop();
            foreach (OutProcessShop outshop in outShopList)
            {
                OutProcessShop_Info info = new OutProcessShop_Info() { OutShopId = outshop.OutShopId, OutShopName = outshop.OutShopName };
                rtnList.Add(info);
            }
            return rtnList.OrderBy(p => p.OutShopName).ToList(); ;
        }
        public DataSet GetAllUnComplateProduct(int inOutSopId)
        {
            return _dal.GetAllUnComplateProduct(inOutSopId);
        }
        public OutProcessShop_Info GetOutShop(int inOutSopId)
        {
            OutProcessShop outshop = _dal.GetOutShop(inOutSopId);
            return new OutProcessShop_Info() { OutShopId = outshop.OutShopId, OutShopName = outshop.OutShopName, EmailAddress = outshop.EmailAddress };
        }
    }
}
